
test();

let msgHandler = {};
msgHandler.getdom = () => {
    let $dom = document.querySelectorAll('.page-top-header-title');
    console.warn(`$dom,`, $dom);
    return { num: $dom.length, $dom };
};

msgHandler.getSudoKuData = () => {
    let $dom = document.querySelector('.sy');
    let $groupNodes = $dom?.childNodes || [];
    let groupNums = [];
    $groupNodes.forEach(a => groupNums.push(getGroupDetail(a)));

    groupNums = groupNums.filter(a => a.length === 9);

    let sudokuNums = turnDomCoordToSudokuCoord(groupNums);

    console.warn(`getSudoKuData,`, JSON.stringify(sudokuNums, undefined, 2));

    return {
        groupNums, sudokuNums
    };
};

msgHandler.show = () => {
    let $container = $(`
    <div id="sudoku-auto-container" style="position: fixed;background: white;top: 100px;left: 0px;z-index: 999;padding: 5px;">
        <strong style="font-size: 20px">Sudoku auto</strong>

        <button id="btn-get-dom">Get Dom</button>
        <button id="btn-calc">Calc</button>
        <button id="btn-close">X</button>

        <div id="popup-container" class="popup-container"></div>
        <div id="calc-result"></div>
    </div>`);
    $container.appendTo('body');

    let $style = $(`
<style>
    
.popup-container {
    border: 3px black solid;
    width: fit-content;
}

.popup-container .row {
    display: flex;
    border-bottom: 1px #ccc solid;
}

.popup-container .row:nth-child(3n):not(:last-child) {
    border-bottom: 3px black solid;
}

.popup-container .row:last-child {
    border-bottom: none !important;
}

.popup-container .row .col {
    width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 18px;
    /* background: #ccc; */
    text-align: center;
    border-right: 1px #ccc solid;
    color: green;
}

.popup-container .row .col:nth-child(3n):not(:last-child) {
    border-right: 3px black solid;
}

.popup-container .row .col:last-child {
    border-right: none !important;
}

.popup-container .row .col.stable {
    font-weight: bold;
    color: black;
}

.popup-container .row .col.cur-calc {
    position: relative;
}

.popup-container .row .col.cur-calc::before {
    content: " ";
    display: inline-block;
    width: 26px;
    height: 26px;
    border: 1px solid red;
    border-radius: 50%;
    position: absolute;
    left: 1px;
    top: 1px;
}

.popup-container .row .col.cur-calc-5::before {
    border: 1px solid rgba(115, 33, 237, 0.727) !important;
}

.col.expect-multi {
    color: #ccc;
    background: yellowgreen;
}
</style>`);

    $style.appendTo('body');

    bindEvent($container, $style);

    // return "show finish";
};

function bindEvent($dom, $style) {
    $dom.find('#btn-get-dom').click(() => {
        const response = msgHandler.getSudoKuData();
        sudoku.sudokuNums = response.sudokuNums;

        // TODO: sidney mock
        // sudoku.sudokuNums = [
        //     [4, 0, 0, 9, 7, 0, 0, 0, 3],
        //     [0, 0, 2, 0, 0, 8, 0, 5, 0],
        //     [0, 0, 0, 0, 1, 0, 0, 0, 0],
        //     [0, 2, 0, 0, 0, 0, 0, 0, 0],
        //     [9, 0, 0, 0, 0, 0, 8, 0, 0],
        //     [0, 8, 0, 0, 9, 5, 0, 0, 6],
        //     [0, 0, 0, 0, 5, 9, 3, 0, 7],
        //     [0, 7, 3, 0, 0, 0, 0, 0, 1],
        //     [0, 0, 4, 0, 6, 0, 0, 0, 0]
        // ];
        // sudoku.sudokuNums = [
        //   [4, 0, 0, 9, 7, 0, 0, 0, 3],
        //   [0, 0, 2, 0, 0, 8, 0, 5, 0],
        //   [0, 0, 0, 0, 1, 0, 0, 0, 0],
        //   [0, 2, 0, 0, 0, 0, 0, 0, 0],
        //   [9, 0, 0, 0, 0, 0, 8, 0, 0],
        //   [0, 8, 0, 0, 9, 5, 0, 0, 6],
        //   [0, 0, 0, 0, 5, 9, 3, 0, 7],
        //   [0, 7, 3, 0, 0, 0, 0, 0, 1],
        //   [0, 0, 4, 0, 6, 0, 0, 0, 0]
        // ];

        sudoku.sudokuObjs = sudoku.sudokuNums.map(a => {
            let row = a.map(b => {
                let item = { num: 0, isStable: false, expect: [] };
                if (b) {
                    item.num = b;
                    item.isStable = true;
                }
                return item;
            });
            return row;
        });

        sudoku.refreshSudoku();
    });


    $dom.find('#btn-calc').click(async () => {
        sudoku.calc();
    });

    $dom.find("#btn-close").click(()=>{
        $dom.remove();
        $style.remove();
    });
}

function getGroupDetail($groupNode) {
    let $nodes = $groupNode?.childNodes || [];
    let nums = [];
    $nodes.forEach(a => nums.push(parseInt(a.innerText)));
    return nums;
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    let msgCode = request.msgCode || '';
    let prefix = 'content-msg-';

    if (!msgCode.startsWith(prefix)) {
        return;
    }

    let method = msgCode.substring(prefix.length);

    if (!msgHandler[method]) {
        console.warn(`missing method: ${method}`);
        return;
    }

    let result = msgHandler[method]();

    sendResponse({ result });
});

function turnDomCoordToSudokuCoordItem(row, col) {
    let resRow = 0;
    let resCol = 0;

    resRow += 3 * Math.floor(row / 3);
    resCol += 3 * (row % 3);

    resRow += Math.floor(col / 3);
    resCol += col % 3;

    return { row: resRow, col: resCol };
}

function turnDomCoordToSudokuCoord(domCoord) {
    let rows = new Array(9).fill(0).map(a => new Array(9).fill(0));

    domCoord.forEach((row, rowindex) => {
        row.forEach((col, colindex) => {
            let obj = turnDomCoordToSudokuCoordItem(rowindex, colindex);
            rows[obj.row][obj.col] = col || 0;
        });
    });

    return rows;
}

function test() {
    let sudokuNums = [
        [0, 9, 0, 0, 0, 0, 0, 7, 3],
        [0, 0, 0, 3, 0, 4, 6, 2, 0],
        [6, 0, 7, 0, 2, 9, 0, 8, 0],
        [0, 0, 0, 0, 1, 6, 0, 0, 8],
        [4, 1, 8, 2, 0, 0, 0, 0, 0],
        [9, 0, 0, 0, 0, 0, 7, 5, 0],
        [0, 0, 0, 1, 0, 0, 3, 0, 7],
        [0, 0, 3, 6, 9, 0, 0, 0, 0],
        [0, 8, 6, 0, 0, 0, 4, 0, 2]
    ];
}
